package com.example.demo.config;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class DemoMessageListener implements MessageListener {

    @Override
    public Action consume(Message message, ConsumeContext context) {
        try {
            //消费消息
            String msgTag = message.getTag();
            String msgBody = new String(message.getBody(), StandardCharsets.UTF_8);
            log.info("接收到MQ消息 -- Topic:{},tag:{},msgId:{},Key:{},body:{}",
                    message.getTopic(), msgTag, message.getMsgID(), message.getKey(),
                    new String(message.getBody()));
            //获取消息重试次数
            int reconsumeTimes = message.getReconsumeTimes();
            log.info("获取消息重试次数为：" + reconsumeTimes);
            //消费成功，继续消费下一条消息
            return Action.CommitMessage;
        } catch (Exception e) {
            log.error("消费MQ消息失败！ msgId:" + message.getMsgID() + " ---Exception:" + e);
            //消费失败，告知服务器稍后再投递这条消息，继续消费其他消息
            return Action.ReconsumeLater;
        }
    }
}
